/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.cms.model.service;

import com.jeeplus.cms.util.CmsCacheUtils;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.cms.column.entity.CmsColumn;
import com.jeeplus.modules.cms.column.service.CmsColumnService;
import com.jeeplus.modules.cms.model.entity.CmsModel;
import com.jeeplus.modules.cms.model.mapper.CmsModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 模型Service
 *
 * @author Sawyer
 * @version 2020-11-21
 */
@Service
@Transactional(readOnly = true)
public class CmsModelService extends CrudService<CmsModelMapper, CmsModel> {

    @Autowired
    private CmsColumnService columnService;

    @Override
    public CmsModel get(String id) {
        return super.get(id);
    }

    @Override
    public List<CmsModel> findList(CmsModel cmsModel) {
        return super.findList(cmsModel);
    }

    @Override
    public List<CmsModel> findAllList(CmsModel entity) {
        return findList(entity);
    }

    @Override
    public Page<CmsModel> findPage(Page<CmsModel> page, CmsModel cmsModel) {
        return super.findPage(page, cmsModel);
    }

    @Override
    @Transactional(readOnly = false)
    public void save(CmsModel cmsModel) {
        super.save(cmsModel);
        // 清除缓存
        CmsCacheUtils.removeCacheBySiteId(CmsCacheUtils.MODEL_LIST_CACHE, cmsModel.getSiteId());
    }

    @Override
    @Transactional(readOnly = false)
    public void delete(CmsModel cmsModel) {
        CmsColumn column = new CmsColumn();
        column.setModel(cmsModel);
        List<CmsColumn> columnList = columnService.findList(column);
        if (null != columnList && columnList.size() > 0) {
            throw new RuntimeException(String.format("模型[%s]已被栏目[%s]关联", cmsModel.getId(), columnList.get(0).getName()));
        }

        String siteId = get(cmsModel.getId()).getSiteId();
        super.delete(cmsModel);
        // 清除缓存
        CmsCacheUtils.removeCacheBySiteId(CmsCacheUtils.MODEL_LIST_CACHE, siteId);
    }

}
